import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as systemApi from '@/api/system'
import type { SystemConfig, AppInfo } from '@/api/system'
import { getPlatformInfo, getDeviceId } from '@/utils/oauth'

export const useAppStore = defineStore('app', () => {
  // 状态
  const systemConfig = ref<SystemConfig | null>(null)
  const appInfo = ref<AppInfo | null>(null)
  const platformInfo = ref(getPlatformInfo())
  const deviceInfo = ref({
    deviceId: getDeviceId(),
    platform: platformInfo.value.platform,
    appVersion: '1.0.0',
    ...uni.getSystemInfoSync()
  })
  const isLoading = ref(false)
  const lastActiveTime = ref(Date.now())
  const networkStatus = ref('unknown')

  // 计算属性
  const isH5 = computed(() => platformInfo.value.platform === 'h5')
  const isWechat = computed(() => platformInfo.value.platform === 'wechat')
  const isAlipay = computed(() => platformInfo.value.platform === 'alipay')
  const isDouyin = computed(() => platformInfo.value.platform === 'douyin')

  const autoLockTime = computed(() => {
    return (systemConfig.value?.auto_logout_minutes || 30) * 60 * 1000
  })

  const enableBiometric = computed(() => {
    return systemConfig.value?.enable_biometric || false
  })

  const enableBackup = computed(() => {
    return systemConfig.value?.enable_backup || false
  })

  const encryptMethods = computed(() => {
    return systemConfig.value?.encrypt_methods || ['AES-256-GCM']
  })

  /**
   * 加载系统配置
   */
  const loadSystemConfig = async () => {
    try {
      isLoading.value = true

      const [config, info] = await Promise.all([
        systemApi.getPublicConfig(),
        systemApi.getAppInfo()
      ])

      systemConfig.value = config
      appInfo.value = info

      // 缓存配置
      uni.setStorageSync('system_config', config)
      uni.setStorageSync('app_info', info)

      return { config, info }

    } catch (error) {
      // 如果网络请求失败，尝试从缓存加载
      const cachedConfig = uni.getStorageSync('system_config')
      const cachedInfo = uni.getStorageSync('app_info')

      if (cachedConfig) {
        systemConfig.value = cachedConfig
      }
      if (cachedInfo) {
        appInfo.value = cachedInfo
      }

      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 检查版本更新
   */
  const checkUpdate = async () => {
    try {
      const currentVersion = deviceInfo.value.appVersion
      const platform = platformInfo.value.platform

      const versionInfo = await systemApi.checkVersion(currentVersion, platform)

      if (versionInfo.has_update) {
        // 显示更新提示
        uni.showModal({
          title: versionInfo.update_info.title,
          content: versionInfo.update_info.description,
          confirmText: '更新',
          cancelText: versionInfo.update_info.force_update ? '' : '取消',
          success: (res) => {
            if (res.confirm && versionInfo.update_info.download_url) {
              // 跳转到下载地址
              // #ifdef H5
              window.open(versionInfo.update_info.download_url)
              // #endif
              // #ifndef H5
              uni.downloadFile({
                url: versionInfo.update_info.download_url,
                success: (downloadRes) => {
                  uni.openDocument({
                    filePath: downloadRes.tempFilePath
                  })
                }
              })
              // #endif
            }
          }
        })
      }

      return versionInfo

    } catch (error) {
      console.error('检查更新失败:', error)
      throw error
    }
  }

  /**
   * 设置平台信息
   */
  const setPlatformInfo = (info: typeof platformInfo.value) => {
    platformInfo.value = info
  }

  /**
   * 设置设备信息
   */
  const setDeviceInfo = (info: Partial<typeof deviceInfo.value>) => {
    deviceInfo.value = { ...deviceInfo.value, ...info }
  }

  /**
   * 设置最后活跃时间
   */
  const setLastActiveTime = (time: number) => {
    lastActiveTime.value = time
  }

  /**
   * 更新网络状态
   */
  const updateNetworkStatus = () => {
    uni.getNetworkType({
      success: (res) => {
        networkStatus.value = res.networkType
      }
    })
  }

  /**
   * 监听网络状态变化
   */
  const watchNetworkStatus = () => {
    // 初始获取网络状态
    updateNetworkStatus()

    // 监听网络状态变化
    uni.onNetworkStatusChange((res) => {
      networkStatus.value = res.networkType

      if (!res.isConnected) {
        uni.showToast({
          title: '网络连接断开',
          icon: 'error'
        })
      }
    })
  }

  /**
   * 获取设备存储信息
   */
  const getStorageInfo = () => {
    try {
      return uni.getStorageInfoSync()
    } catch (error) {
      console.error('获取存储信息失败:', error)
      return {
        keys: [],
        currentSize: 0,
        limitSize: 0
      }
    }
  }

  /**
   * 清理缓存
   */
  const clearCache = async () => {
    try {
      // 保留重要数据
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('user_info')
      const masterPassword = uni.getStorageSync('master_password')

      // 清空所有存储
      uni.clearStorageSync()

      // 恢复重要数据
      if (token) uni.setStorageSync('token', token)
      if (userInfo) uni.setStorageSync('user_info', userInfo)
      if (masterPassword) uni.setStorageSync('master_password', masterPassword)

      uni.showToast({
        title: '缓存清理完成',
        icon: 'success'
      })

    } catch (error) {
      console.error('清理缓存失败:', error)
      throw error
    }
  }

  /**
   * 提交用户反馈
   */
  const submitFeedback = async (data: systemApi.FeedbackData) => {
    try {
      const feedbackData = {
        ...data,
        device_info: deviceInfo.value
      }

      return await systemApi.submitFeedback(feedbackData)

    } catch (error) {
      throw error
    }
  }

  /**
   * 初始化应用状态
   */
  const initAppState = () => {
    try {
      // 从存储恢复配置
      const cachedConfig = uni.getStorageSync('system_config')
      const cachedInfo = uni.getStorageSync('app_info')

      if (cachedConfig) {
        systemConfig.value = cachedConfig
      }
      if (cachedInfo) {
        appInfo.value = cachedInfo
      }

      // 监听网络状态
      watchNetworkStatus()

    } catch (error) {
      console.error('初始化应用状态失败:', error)
    }
  }

  /**
   * 重置应用状态
   */
  const resetAppState = () => {
    systemConfig.value = null
    appInfo.value = null
    lastActiveTime.value = Date.now()
    networkStatus.value = 'unknown'
  }

  return {
    // 状态
    systemConfig,
    appInfo,
    platformInfo,
    deviceInfo,
    isLoading,
    lastActiveTime,
    networkStatus,

    // 计算属性
    isH5,
    isWechat,
    isAlipay,
    isDouyin,
    autoLockTime,
    enableBiometric,
    enableBackup,
    encryptMethods,

    // 方法
    loadSystemConfig,
    checkUpdate,
    setPlatformInfo,
    setDeviceInfo,
    setLastActiveTime,
    updateNetworkStatus,
    watchNetworkStatus,
    getStorageInfo,
    clearCache,
    submitFeedback,
    initAppState,
    resetAppState
  }
})